import { getLoginUser, destorySession } from '@/api/auth';
import { defineStore } from 'pinia';
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import type { LoginUser } from '@/model/System';
import router from '@/router';

const USER_KEY = 'user';

const defaultUser: LoginUser = {
  token: '',
  account: '',
  name: '',
  roles: [],
  permissions: [],
};

export const userStore = defineStore('user', () => {
  const user = ref<LoginUser>(JSON.parse(localStorage.getItem(USER_KEY) || JSON.stringify(defaultUser)));
  const login = async () => {
    const res: LoginUser = await getLoginUser();
    if (res.token) {
      user.value = res;
      localStorage.setItem(USER_KEY, JSON.stringify(res));
      ElMessage.success('login success');
      console.log('login success');
    } else {
      ElMessage.success('login fail');
      console.log('login fail');
    }
  };
  const logout = () => {
    localStorage.removeItem(USER_KEY);
    user.value = defaultUser;
    ElMessage.success('logout success');
    console.log('logout success');
    destorySession();
    router.push('/home');
  };
  return { user, login, logout };
});
